from django.shortcuts import render, redirect

from django.contrib.auth.models import User, Group
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import get_object_or_404, redirect
from django import forms

# 用户表单
class UserForm(forms.ModelForm):
    password = forms.CharField(label="密码", widget=forms.PasswordInput(), required=False)
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(), required=False)
    groups = forms.ModelMultipleChoiceField(
        label="用户组",
        queryset=Group.objects.all(),
        widget=forms.CheckboxSelectMultiple(),
        required=False
    )
    
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', 'groups']
    
    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')
        
        # 密码和确认密码必须匹配
        if password and password != confirm_password:
            raise forms.ValidationError("密码和确认密码不匹配")
        
        return cleaned_data

# Dashboard view
@login_required
def dashboard_view(request):
    # You can add context data here if needed
    context = {
        'title': '仪表盘',
        'welcome_message': 'Welcome to the Dashboard!'
    }
    return render(request, 'dashboard/dashboard.html', context)

from demo.settings import CHART_TITLE_1, CHART_TITLE_2, CHART_TITLE_3

# Data Charts 1 view
@login_required
def data_charts_1_view(request):
    context = {
        'title': CHART_TITLE_1,
        'page_title': CHART_TITLE_1,
        'breadcrumb_active': '数据可视化 / ' + CHART_TITLE_1
    }
    return render(request, 'dashboard/data_charts_1.html', context)

# Data Charts 2 view
@login_required
def data_charts_2_view(request):
    context = {
        'title': CHART_TITLE_2,
        'page_title': CHART_TITLE_2,
        'breadcrumb_active': '数据可视化 / ' + CHART_TITLE_2
    }
    return render(request, 'dashboard/data_charts_2.html', context)

# Data Charts 3 view
@login_required
def data_charts_3_view(request):
    context = {
        'title': CHART_TITLE_3,
        'page_title': CHART_TITLE_3,
        'breadcrumb_active': '数据可视化 / ' + CHART_TITLE_3
    }
    return render(request, 'dashboard/data_charts_3.html', context)

# 用户列表视图
@login_required
@user_passes_test(lambda u: u.is_superuser)
def user_list_view(request):
    users = User.objects.all().order_by('username')
    context = {
        'title': '用户列表',
        'page_title': '用户列表',
        'breadcrumb_active': '用户管理 / 用户列表',
        'users': users
    }
    return render(request, 'dashboard/user_list.html', context)

# 添加用户视图
@login_required
@user_passes_test(lambda u: u.is_superuser)
def add_user_view(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            # 如果提供了密码，则设置密码
            if form.cleaned_data['password']:
                user.set_password(form.cleaned_data['password'])
            user.save()
            # 保存用户组
            if form.cleaned_data['groups']:
                user.groups.set(form.cleaned_data['groups'])
            messages.success(request, '用户添加成功！')
            return redirect('user_list')
    else:
        form = UserForm()
    
    context = {
        'title': '添加用户',
        'page_title': '添加用户',
        'breadcrumb_active': '用户管理 / 添加用户',
        'form': form
    }
    return render(request, 'dashboard/add_user.html', context)

# 编辑用户视图
@login_required
@user_passes_test(lambda u: u.is_superuser)
def edit_user_view(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    
    if request.method == 'POST':
        form = UserForm(request.POST, instance=user)
        if form.is_valid():
            # 如果提供了密码，则设置密码
            if form.cleaned_data['password']:
                user.set_password(form.cleaned_data['password'])
            user.save()
            # 保存用户组
            if form.cleaned_data['groups']:
                user.groups.set(form.cleaned_data['groups'])
            messages.success(request, '用户更新成功！')
            return redirect('user_list')
    else:
        form = UserForm(instance=user)
    
    context = {
        'title': '编辑用户',
        'page_title': '编辑用户',
        'breadcrumb_active': '用户管理 / 编辑用户',
        'form': form,
        'user': user
    }
    return render(request, 'dashboard/edit_user.html', context)

# 删除用户视图
@login_required
@user_passes_test(lambda u: u.is_superuser)
def delete_user_view(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    
    # 不允许删除当前登录用户
    if user == request.user:
        messages.error(request, '不能删除当前登录的用户！')
        return redirect('user_list')
    
    # 不允许删除唯一的超级用户
    superusers = User.objects.filter(is_superuser=True)
    if user.is_superuser and len(superusers) <= 1:
        messages.error(request, '不能删除系统中唯一的超级用户！')
        return redirect('user_list')
    
    if request.method == 'POST':
        user.delete()
        messages.success(request, '用户已成功删除！')
        return redirect('user_list')
    
    context = {
        'title': '删除用户',
        'page_title': '删除用户',
        'breadcrumb_active': '用户管理 / 删除用户',
        'user': user
    }
    return render(request, 'dashboard/delete_user.html', context)

# 基本设置视图
@login_required
def basic_setting_view(request):
    # 有效主题列表
    available_themes = ['default', 'blue', 'green', 'purple', 'red', 'yellow', 'black']
    
    # 获取当前主题
    current_theme = request.session.get('adminlte_theme', 'default')
    
    context = {
        'title': '基本设置',
        'page_title': '基本设置',
        'breadcrumb_active': '系统设置 / 基本设置',
        'available_themes': available_themes,
        'current_theme': current_theme
    }
    
    return render(request, 'dashboard/basic_setting.html', context)

# 更改主题视图
@login_required
def change_theme(request):
    # 支持GET和POST请求
    if request.method in ['GET', 'POST']:
        # 根据请求方法获取主题参数
        theme = request.POST.get('theme') if request.method == 'POST' else request.GET.get('theme')
        
        # 有效主题列表
        valid_themes = ['default', 'blue', 'green', 'purple', 'red', 'yellow', 'black']
        
        # 检查主题是否有效
        if theme and theme in valid_themes:
            # 存储主题到会话
            request.session['adminlte_theme'] = theme
            # 强制保存会话
            request.session.save()
    
    # 获取来源URL，如果没有则返回到dashboard
    referer = request.META.get('HTTP_REFERER')
    if referer:
        return redirect(referer)
    return redirect('dashboard')
